package com.hnjfzn.system.service.impl;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.hnjfzn.common.security.utils.SecurityUtils;
import com.hnjfzn.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.hnjfzn.common.core.constant.UserConstants;
import com.hnjfzn.common.core.utils.StringUtils;
import com.hnjfzn.system.api.domain.SysRole;
import com.hnjfzn.system.api.domain.SysUser;

/**
 * 用户权限处理

 */
@Service
public class SysPermissionServiceImpl implements ISysPermissionService
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysInfoService infoService;

    /**
     * 获取角色数据权限
     * 
     * @return 角色权限信息
     */
    @Override
    public Set<String> getRolePermission()
    {
        // 用户标识
        Long userId = SecurityUtils.getUserId();
        // 角色信息
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(userId))
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(roleService.selectRolePermissionByUserId(userId));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(Set<String> roles)
    {
        // 用户标识
        Long userId = SecurityUtils.getUserId();
        // 权限信息
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(userId))
        {
            perms.add("*:*:*");
        }
        else
        {
            if (!CollectionUtils.isEmpty(roles))
            {
                // 根据角色获取权限信息
                perms.addAll(menuService.selectMenuPermsByRoleKey(new ArrayList<>(roles)));
            }
            else
            {
                perms.addAll(menuService.selectMenuPermsByUserId(userId));
            }
        }
        return perms;
    }

    @Override
    public Map<String, Object> getSysPermission(SysUser user) {
        Map<String, Object> infos;
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            infos = infoService.all();
        }
        else
        {
            infos = infoService.selectSysPermsByUserId(user.getUserId());
        }
        return infos;
    }
}
